{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用 LangChain 实现 AutoGPT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip -q install  openai tiktoken\n",
    "%pip install git+https://github.com/hwchase17/langchain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"\"\n",
    "# SERPAPI_API_KEY\n",
    "os.environ[\"SERPAPI_API_KEY\"] = \"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们来设置一些工具，这包括搜索工具、写文件工具和读文件工具，这些都是为了让AutoGPT能够更好地完成任务。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.utilities import SerpAPIWrapper\n",
    "from langchain.agents import Tool\n",
    "from langchain.tools.file_management.write import WriteFileTool\n",
    "from langchain.tools.file_management.read import ReadFileTool\n",
    "\n",
    "search = SerpAPIWrapper()\n",
    "tools = [\n",
    "    Tool(\n",
    "        name=\"search\",\n",
    "        func=search.run,\n",
    "        description=\"useful for when you need to answer questions about current events. You should ask targeted questions\",\n",
    "    ),\n",
    "    WriteFileTool(),\n",
    "    ReadFileTool(),\n",
    "]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "设置内存，这是用于存储模型在执行任务过程中的中间步骤。这对于理解模型的工作过程和改进模型的性能都非常重要。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.vectorstores import FAISS\n",
    "from langchain.docstore import InMemoryDocstore\n",
    "from langchain.embeddings import OpenAIEmbeddings"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们使用OpenAI 的嵌入模型, 向量库使用 FAISS。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define your embedding model\n",
    "embeddings_model = OpenAIEmbeddings()\n",
    "# Initialize the vectorstore as empty\n",
    "import faiss\n",
    "\n",
    "embedding_size = 1536\n",
    "index = faiss.IndexFlatL2(embedding_size)\n",
    "vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在设置好工具和内存后，初始化模型和AutoGPT。我们选择的模型是ChatOpenAI，这是一个专为对话设计的大语言模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.experimental import AutoGPT\n",
    "from langchain.chat_models import ChatOpenAI"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Langchain 已经封装好 AutoGPT 类，我们通过 from_llm_and_tools 方法可以实例化这个类。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = AutoGPT.from_llm_and_tools(\n",
    "    ai_name=\"Tom\",\n",
    "    ai_role=\"Assistant\",\n",
    "    tools=tools,\n",
    "    llm=ChatOpenAI(temperature=0),\n",
    "    memory=vectorstore.as_retriever(),\n",
    ")\n",
    "# Set verbose to be true\n",
    "agent.chain.verbose = True"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，运行一个示例，让AutoGPT为旧金山编写一份天气报告。这展示了AutoGPT在实际应用中的能力。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "agent.run([\"上海最近都要下雨吗？\"])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "最后，设置聊天历史记录的内存。这是除了用于存储模型中间步骤的内存之外的另一种内存。这种内存默认使用'ChatMessageHistory'，但可以改变。当你希望使用不同类型的内存，例如'FileChatHistoryMemory'时，这将非常有用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.memory.chat_message_histories import FileChatMessageHistory\n",
    "\n",
    "agent = AutoGPT.from_llm_and_tools(\n",
    "    ai_name=\"Tom\",\n",
    "    ai_role=\"Assistant\",\n",
    "    tools=tools,\n",
    "    llm=ChatOpenAI(temperature=0),\n",
    "    memory=vectorstore.as_retriever(),\n",
    "    chat_history_memory=FileChatMessageHistory(\"chat_history.txt\"),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "agent.run([\"write a weather report for Shanghai today\"])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
